﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using System.ServiceProcess;
using Microsoft.TeamFoundation.Build.Client;

namespace TeamDeploy.Activities
{
    [BuildActivity(HostEnvironmentOption.Agent)]
    public sealed class StopService : CustomActivityBase
    {
        // Define an activity input argument of type string
        public InArgument<string> ServiceName { get; set; }
        public InArgument<string> TargetMachine { get; set; }

        // If your activity returns a value, derive from CodeActivity<TResult>
        // and return the value from the Execute method.
        protected override void Execute(CodeActivityContext context)
        {
            // Obtain the runtime value of the Text input argument
            string serviceName = context.GetValue(this.ServiceName);
            string targetMachine = context.GetValue(this.TargetMachine);

            try
            {
                ServiceController controller = new ServiceController(serviceName, targetMachine);

                try
                {
                    if (!controller.CanStop)
                        return;
                }
                catch (Exception)
                {
                    throw new Exception("Stop Service: " + serviceName + " on " + targetMachine + " doesn't exist.");
                }

                if (controller != null && controller.CanStop)
                {
                    controller.Stop();
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
